﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SAP.People
{
    class MergeTask : ITask
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SpiderContext context;

        public MergeTask(SpiderContext ctx)
        {
            context = ctx;
        }

        public void RunSynchronously()
        {
            using (var s = new StreamWriter(context.OutputFile))
            {
                s.WriteLine(CreateCsvHeader());

                foreach (var employee in context.Employees)
                {
                    var json = Path.Combine(context.IntermediateDir, employee.UserId + ".json");
                    var raw = File.ReadAllText(json);
                    var data = JsonConvert.DeserializeObject<Employee>(raw);
                    s.WriteLine(ToCsv(data, employee));
                }
            }
            log.InfoFormat("CSV file {0} created", context.OutputFile);
        }

        private string CreateCsvHeader()
        {
            var sb = new StringBuilder();

            sb.Append("UserId");
            sb.Append(',');
            sb.Append("Alias");
            sb.Append(',');
            sb.Append("FullName");
            sb.Append(',');
            sb.Append("NumberOfChildren");
            sb.Append(',');
            sb.Append("JobTitle");
            sb.Append(',');
            sb.Append("JobType");
            sb.Append(',');
            sb.Append("GradeLevel");
            sb.Append(',');
            sb.Append("Email");
            sb.Append(',');
            sb.Append("Mobile");
            sb.Append(',');
            sb.Append("Manager");
            //sb.Append(',');

            return sb.ToString();
        }

        private string ToCsv(Employee fork, Employee ordinal)
        {
            var sb = new StringBuilder();

            sb.Append(fork.UserId);
            sb.Append(',');
            sb.Append(fork.Alias);
            sb.Append(',');
            sb.Append(fork.FullName);
            sb.Append(',');
            sb.Append(fork.NumberOfChildren);
            sb.Append(',');
            sb.Append(Encode(fork.JobTitle));
            sb.Append(',');
            sb.Append(Encode(fork.JobType));
            sb.Append(',');
            sb.Append(fork.GradeLevel);
            sb.Append(',');
            sb.Append(fork.Email);
            sb.Append(',');
            sb.Append(fork.Mobile);
            sb.Append(',');
            sb.Append(ordinal.ManagerName);
            //sb.Append(',');

            return sb.ToString();
        }

        private string Encode(string v)
        {
            return v.Replace(',', ';');
        }
    }
}
